<template>
  <div style="background-color:white;height:100%;width:500px" @contextmenu.prevent="" @keydown.ctrl.80.prevent="">
    <canvas v-for="page in pages" :id="'the-canvas'+page" :key="page"></canvas>
    <!-- <div class="pdfList"  style="position:relative;overflow:auto;">
         <pdf
            v-for="i in numPages"
            ref="pdf"
            :src="pdfSrc"
            :key="i"
            :page="i" >
        </pdf>
    </div>
    <div class="pdfLista"  style="position:relative;overflow:auto;">
    </div> -->
 </div>
</template>

<script>
import pdf from 'vue-pdf'
import {neturl} from '../assets/js/common'
import PDFJS from 'pdfjs-dist'
export default {
  data () {
    return {
      pdfSrc: '',
      scale: 100,
      numPages: 0,
      pdfDataList: '',
      pdfUrla: '',
      pdfDoc: '',
      pages: ''
    }
  },
  created () {
    // PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.min.js')
    let taddress = this.$route.query.textaddress
    let upload = { data: taddress }
    this.$axios.post(neturl + '/by/standard/preview', upload).then(res => {
      // console.log(res)
      // console.log(taddress)
      if (res.data.code === 400) {
        this.$Message.error('抱歉当前标准电子文档丢失!')
      } else {
        this.getPageNum(res.data.data.result)
      }
      // this.pdfDataList = res.data.data.result
      // this.showPdf()
      // let URL = this.dataURLtoBlob(res.data.data.result)
      // var reader = new FileReader()
      // reader.readAsDataURL(URL)
      // reader.onload = function (e) {
      // this.pdfUrl = e.target.result
      // this.pdfSrc = e.target.result
      // this.getPageNum()
      // this.pdfUrl = pdf.createLoadingTask(this.src)
      // this.pdfUrl.then(pdf => {
      //   this.numPages = pdf.numPages
      // })
      // }
    })
  },
  mounted () {
    // this.loadPdfHandler()
    // this.$refs.shuxingBox.oncontextmenu = function () { return false }
  },
  methods: {
    loadPdfHandler () {
      // src为你服务器上存放pdf的路径
      this.pdfUrl = pdf.createLoadingTask(this.src)
      this.pdfUrl.then(pdf => {
        this.numPages = pdf.numPages
      })
    },
    dataURLtoBlob (dataurl) {
      var bstr = atob(dataurl)
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: 'pdf' })
    },
    async getPageNum (res) {
      // var decodedBase64 = atob(res)
      // var pdf = await PDFJS.getDocument({data: decodedBase64})
      // this.numPages = pdf.numPages
      // this.pdfSrc = `data:pdf;base64,${res}` // application/
      this._loadFile(`data:pdf;base64,${res}`)
      // this.pdfSrc = pdf
      // this.pdfUrla = `data:pdf;base64,${res}`
      // this.pdfSrc = res
    },
    scaleAdd () {
      if (this.scale === 300) return
      this.scale += 10
      for (var i in this.$refs.pdf) {
        this.$refs.pdf[i].$el.style.width = parseInt(this.scale) + '%'
      }
    },
    scaleReduce () {
      if (this.scale === 100) {
        return
      }
      this.scale += -10
      for (var i in this.$refs.pdf) {
        this.$refs.pdf[i].$el.style.width = parseInt(this.scale) + '%'
      }
    },
    async showPdf () {
      let pdfList = document.querySelector('.pdfLista') // 通过querySelector选择DOM节点,使用document.getElementById()也一样
      let base64 = this.pdfDataList // 获得bas464编码
      // console.log(base64)
      let decodedBase64 = atob(base64) // 使用浏览器自带的方法解码
      let pdf = await PDFJS.getDocument({data: decodedBase64}) // 返回一个pdf对象
      let pages = pdf.numPages // 声明一个pages变量等于当前pdf文件的页数
      for (let i = 1; i <= pages; i++) { // 循环页数
        let canvas = document.createElement('canvas')
        let page = await pdf.getPage(i) // 调用getPage方法传入当前循环的页数,返回一个page对象
        let scale = 1// 缩放倍数，1表示原始大小
        // let width = document.body.clientWidth // 窗口的宽度
        let viewport = page.getViewport(scale)
        let context = canvas.getContext('2d')// 创建绘制canvas的对象
        canvas.height = viewport.height // 定义canvas高和宽
        canvas.width = viewport.width
        // canvas.width = 300
        let renderContext = {
          canvasContext: context,
          viewport: viewport
        }
        await page.render(renderContext)
        canvas.className = 'canvas' // 给canvas节点定义一个class名,这里我取名为canvas
        pdfList.appendChild(canvas) // 插入到pdfList节点的最后
      }
    },
    getObjectURL (file) {
      let url = null
      if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(file)
      } else if (window.webkitURL !== undefined) { // webkit or chrome
        try {
          url = window.webkitURL.createObjectURL(file)
        } catch (error) {
          // console.log(error)
        }
      } else if (window.URL !== undefined) { // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(file)
        } catch (error) {
          // console.log(error)
        }
      }
      return url
    },
    _renderPage (num) {
      this.pdfDoc.getPage(num).then((page) => {
        let canvas = document.getElementById('the-canvas' + num)
        let ctx = canvas.getContext('2d')
        let dpr = window.devicePixelRatio || 1
        let bsr = ctx.webkitBackingStorePixelRatio ||
         ctx.mozBackingStorePixelRatio ||
         ctx.msBackingStorePixelRatio ||
         ctx.oBackingStorePixelRatio ||
         ctx.backingStorePixelRatio || 1
        let ratio = dpr / bsr
        let viewport = page.getViewport(screen.availWidth / page.getViewport(1).width)
        canvas.width = viewport.width * ratio
        canvas.height = viewport.height * ratio
        canvas.style.width = viewport.width + 'px'
        canvas.style.height = viewport.height + 'px'
        ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
        let renderContext = {
          canvasContext: ctx,
          viewport: viewport
        }
        page.render(renderContext)
        if (this.pages > num) {
          this._renderPage(num + 1)
        }
      })
    },
    _loadFile (url) {
      PDFJS.getDocument(url).then((pdf) => {
        this.pdfDoc = pdf
        // console.log(pdf)
        this.pages = this.pdfDoc.numPages
        this.$nextTick(() => {
          this._renderPage(1)
        })
      })
    }
  },
  components: {
    pdf
  }
}

</script>

<style scoped>
  @media print{
    body{display:none}
  }
</style>
